import { Button, message, Modal,Divider } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { PlusOutlined ,ExclamationCircleOutlined} from '@ant-design/icons';
import { queryTask, addTask, updateTask, updateTaskState,removeTask } from '@/services/task';
const { confirm } = Modal;

import styles from '@/global.less';


/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在添加');
  try {
    console.log(fields)
    await addTask(fields);
    hide();
    resetForm();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any,resetForm: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateTask(fields);
    hide();
    resetForm();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};

//删除单个
const remove = async (departmentId: number) => {
  const hide = message.loading('正在删除');
  try {
    await removeTask({ departmentId });
    hide();

    message.success('删除成功，正在刷新！');

    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};





const DeviceAttr: React.FC = () => {

const [createModalVisible, handleModalVisible] = useState<boolean>(false);
const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
const [formValues, setFormValues] = useState({});
const [selectedRowsState, setSelectedRows] = useState<API.DepartmentItem[]>([]);

const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [   
    {
    title: 'ID',
    search: false,
    dataIndex: 'id',
  },
  {
    title: '任务名称',
    dataIndex: 'jobName',
  
  },
   {
      title: '任务描述',
      dataIndex: 'description',
    },
    {
      title: 'cron表达式',
      dataIndex: 'cronExpression',
    },
    {
      title: '任务执行时调用的包名+类名',
      dataIndex: 'beanClass',
    },
    {
      title: '任务状态',
      dataIndex: 'jobStatus',
      valueEnum: {'1':'执行中','0':'停止'},
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>{ record.jobStatus=='0' ?<a
        key="run"
        onClick={() => {
          confirm({
            title: '您确定要立即执行定时任务吗?',
            icon: <ExclamationCircleOutlined />,
            async onOk() {
               await updateTaskState({id:record.id,state:1});
              actionRef.current?.reload();
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
      >
        执行
      </a>:<a
     
        onClick={() => {
          confirm({
            title: '您确定要关闭定时任务吗?',
            icon: <ExclamationCircleOutlined />,
            async onOk() {
              await updateTaskState({id:record.id,state:0});
              actionRef.current?.reload();
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        }}
      >
       关闭
      </a>}
      <Divider type="vertical" />
        <a
          key="editable"
          onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a></>
      )
    },
  ];
  useEffect(() => {
 
  }, []);


  return (
    <>
      <ProTable
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary"  className={styles.addBtn} onClick={() => handleModalVisible(true)}>
            新增
          </Button>,
       
        ]}
        rowSelection={false}
        search={false}
        options={false}
        actionRef={actionRef}
        tableAlertRender={false}
        columns={columns}
        request={(params) => queryTask(params)}
      />
     <CreateForm
        onSubmit={async (value,resetForm) => {
          const success = await handleAdd(value,resetForm);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      
      />
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value,resetForm) => {
            const success = await handleUpdate(value,resetForm);
            if (success) {
              handleModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
        
        />
      ) : null}
    </>
  );
};

export default DeviceAttr;



